package com.guochenglang.www.service.impl;

import com.guochenglang.www.dao.MemberDao;
import com.guochenglang.www.pojo.Member;
import com.guochenglang.www.service.MemberService;
import com.guochenglang.www.service.anotate.Affair;
import com.guochenglang.www.util.MyDependency;

import java.sql.SQLException;
import java.util.ArrayList;

/**
 * 成员业务
 *
 * @author GuoChenglang
 */
public class MemberServiceImpl implements MemberService {
    private static final MemberDao MEMBER_DAO = MyDependency.returnObject(MemberDao.class);


    /**
     * 修改成员状态
     *
     * @param newMember 更改的信息
     * @param userId    用户id
     * @return 修改行数
     */
    @Affair
    @Override
    public int changeMember(Member newMember, int userId) throws SQLException, InterruptedException, IllegalAccessException, InstantiationException {
        int baseId = newMember.getBaseId();
        //检测是否为创建者
        ArrayList<Member> members = null;
        //搜索成员
        members = MEMBER_DAO.memberSelect(new Member(null, baseId, "1", userId));
        if (!members.isEmpty()) {
            //修改成员状态
            Member oldMember = new Member();
            oldMember.setId(newMember.getId());
            return MEMBER_DAO.updateMember(newMember, oldMember);
        } else {
            return -1;
        }
    }

    /**
     * 删除成员
     *
     * @param memberId 成员id
     * @param userId   执行者用户id
     * @return 删除行数
     */
    @Affair
    @Override
    public int deleteMember(int memberId, int userId) throws IllegalAccessException, InstantiationException, SQLException, InterruptedException {
        //根据id获得成员
        Member memberCondition = new Member();
        memberCondition.setId(memberId);
        Member beDelete = baseMemberList(memberCondition).get(0);
        int baseId = beDelete.getBaseId();
        //查看成员的权限
        String beDeleteStatus = beDelete.getMemberStatus();
        //查看用户的权限
        String userStatus = baseMemberList(new Member(null, baseId, null, userId)).get(0).getMemberStatus();
        //权限比较大，删除成功
        if (userStatus.compareTo(beDeleteStatus) < 0) {
            return MEMBER_DAO.deleteMember(memberCondition);
        } else {
            //权限小，删除失败
            return -1;
        }
    }

    /**
     * 获得知识库成员列表
     *
     * @param conditions 搜索条件
     * @return 成员列表
     */
    @Override
    public ArrayList<Member> baseMemberList(Member conditions) throws SQLException, InterruptedException, IllegalAccessException, InstantiationException {
        return MEMBER_DAO.memberSelect(conditions);
    }
}
